package com.theta.gateway.infra.common.utils;

import java.math.BigDecimal;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.alibaba.fastjson.JSONObject;


/**
 */
public class StrUtil {

	private static Pattern linePattern = Pattern.compile("_(\\w)");

	/**
	 * 获取字符串长度，中文三个字节
	 * 
	 * @param s
	 * @return
	 */
	public static int getWordCount(String s) {
		s = s.replaceAll("[^\\x00-\\xff]", "***");
		int length = s.length();
		return length;
	}

	public static boolean isEmpty(Object paramObject) {
		return (paramObject == null) || (paramObject.toString().trim().length() == 0);
	}

	public static boolean isNotEmpty(Object paramObject) {
		return !isEmpty(paramObject);
	}

	public static boolean isNumber(Object paramObject) {
		boolean bool = false;
		if (paramObject == null) {
			return bool;
		}
		return paramObject.toString().trim().matches("^-?\\d+[\\.\\d]*$");
	}

	public static String null2string(Object paramObject) {
		return paramObject == null ? "" : paramObject.toString();
	}

	public static String null2string(Object paramObject, String paramString) {
		return isEmpty(paramObject) ? paramString : paramObject.toString();
	}

	public static Integer obj2Integer(Object paramObject, Integer paramInteger) {
		if (isEmpty(paramObject)) {
			return paramInteger;
		}
		return Integer.valueOf(paramObject.toString());
	}

	public static Integer obj2Integer(Object paramObject) {
		return obj2Integer(paramObject, Integer.valueOf(0).intValue());
	}

	public static Long obj2Long(Object paramObject) {
		return obj2Long(paramObject, Long.valueOf(0).longValue());
	}

	public static Long obj2Long(Object paramObject, Long paramInteger) {
		if (isEmpty(paramObject)) {
			return paramInteger;
		}
		return Long.valueOf(paramObject.toString());
	}

	public static BigDecimal obj2BigDecimal(Object paramObject) {
		if (isEmpty(paramObject)) {
			return null;
		}
		return new BigDecimal(paramObject.toString());
	}

	public static int getRandNumber(int length) {
		int i = (int) Math.pow(10.0D, length - 1);
		int j = (int) Math.pow(10.0D, length) - 1 - i;
		double d = Math.random() * j + i;
		return (int) d;
	}

	public static int getRandomNum(int max) {
		Random r = new Random();
		if (max == 0) {
			return r.nextInt();
		}
		return r.nextInt(max);
	}

	/**
	 * 产生一个介于 min和max之间的数字 min<= num <=max
	 * 
	 * @param min
	 * @param max
	 * @return
	 */
	public static int getRandomNumber(int min, int max) {
		return new Random().nextInt(max - min + 1) + min;
	}

	public static String getUUID() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	/**
	 * 内容是否包含特殊字符
	 * 
	 * @param content
	 * @return
	 */
	public static boolean containSpecialCharacter(String content, String regEx) {
		if (isEmpty(content)) {
			return false;
		}
		if (isEmpty(regEx)) {
			regEx = "[ _`~!@#$%^&*()+=|{}':;'\\[\\].<>/?~！@#￥%……&*——+|{}‘；：”“’]|\n|\r|\t";
		}
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(content);
		return m.find();
	}

	/**
	 * 判断字符串是否是json格式
	 */
	public static boolean isJsonStr(String str) {
		boolean result = false;
		try {
//            Object obj=JSON.parse(str);;
			JSONObject obj = JSONObject.parseObject(str);
			result = true;
		} catch (Exception e) {
			result = false;
		}
		return result;
	}

	/** 下划线转驼峰 */
	public static String lineToHump(String str) {
		str = str.toLowerCase();
		Matcher matcher = linePattern.matcher(str);
		StringBuffer sb = new StringBuffer();
		while (matcher.find()) {
			matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
		}
		matcher.appendTail(sb);
		return sb.toString();
	}
	
	public static boolean matches(String pattern, String source) {
        if (pattern != null && source != null) {
            pattern = pattern.trim();
            source = source.trim();
            int start;
            if (pattern.endsWith("*")) {
                start = pattern.length() - 1;
                if (source.length() >= start && pattern.substring(0, start).equals(source.substring(0, start))) {
                    return true;
                }
            } else if (pattern.startsWith("*")) {
                start = pattern.length() - 1;
                if (source.length() >= start && source.endsWith(pattern.substring(1))) {
                    return true;
                }
            } else if (pattern.contains("*")) {
                start = pattern.indexOf("*");
                int end = pattern.lastIndexOf("*");
                if (source.startsWith(pattern.substring(0, start)) && source.endsWith(pattern.substring(end + 1))) {
                    return true;
                }
            } else if (pattern.equals(source)) {
                return true;
            }
            return false;
        } else {
            return false;
        }
    }
    
    /**
     * 将/*结尾的url转换成[/**   ]
     * @param url
     * @return
     */
    public static String urlFormat(String url) {
    	return url.endsWith("/*")?url.replace("/*", "/**"):url;
    }
    /**
     * 将/**结尾的url转换成[/*  ]
     * @param url
     * @return
     */
    public static String urlFormat2(String url) {
    	return url.endsWith("/**")?url.replace("/**", "/*"):url;
    }
    
    public static boolean compileKeyWord(String word, String keyWord) {
        Pattern pn = Pattern.compile(keyWord+"\\w|\\w"+keyWord+"\\w|\\w"+keyWord); 
       Matcher mr = null; 
      mr = pn.matcher(word);
      if (mr.find())  {
        return true;
      } else {
        return false;
      }
   }
    
    public static boolean isMatchPattern(String s, String p) {
        int m = s.length();
        int n = p.length();
        boolean[][] dp = new boolean[m + 1][n + 1];
        dp[0][0] = true;
        for (int i = 1; i <= n; ++i) {
            if (p.charAt(i - 1) == '*') {
                dp[0][i] = true;
            } else {
                break;
            }
        }
        for (int i = 1; i <= m; ++i) {
            for (int j = 1; j <= n; ++j) {
                if (p.charAt(j - 1) == '*') {
                    dp[i][j] = dp[i][j - 1] || dp[i - 1][j];
                } else if (p.charAt(j - 1) == '?' || s.charAt(i - 1) == p.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                }
            }
        }
        return dp[m][n];
    }
    
    public static boolean isMatch(String s, String p) {
        int sRight = s.length(), pRight = p.length();
        while (sRight > 0 && pRight > 0 && p.charAt(pRight - 1) != '*') {
            if (charMatch(s.charAt(sRight - 1), p.charAt(pRight - 1))) {
                --sRight;
                --pRight;
            } else {
                return false;
            }
        }

        if (pRight == 0) {
            return sRight == 0;
        }

        int sIndex = 0, pIndex = 0;
        int sRecord = -1, pRecord = -1;
        
        while (sIndex < sRight && pIndex < pRight) {
            if (p.charAt(pIndex) == '*') {
                ++pIndex;
                sRecord = sIndex;
                pRecord = pIndex;
            } else if (charMatch(s.charAt(sIndex), p.charAt(pIndex))) {
                ++sIndex;
                ++pIndex;
            } else if (sRecord != -1 && sRecord + 1 < sRight) {
                ++sRecord;
                sIndex = sRecord;
                pIndex = pRecord;
            } else {
                return false;
            }
        }

        return allStars(p, pIndex, pRight);
    }

    public static boolean allStars(String str, int left, int right) {
        for (int i = left; i < right; ++i) {
            if (str.charAt(i) != '*') {
                return false;
            }
        }
        return true;
    }

    public static boolean charMatch(char u, char v) {
        return u == v || v == '?';
    }


    
    public static void main(String[] args) {
    	String pattern="/gbs/admin/**";
    	System.out.println(matches(pattern, "/gbs/admin/admin/*"));
    	pattern="\\wException\\w"; //keyWord+"\\w|\\w"+keyWord+"\\w|\\w"+keyWord
    	String msg="com.netflix.client.ClientException: Load balancer does not have available server for client: saas-sso-core";
    	Pattern pn = Pattern.compile(pattern); 
        Matcher mr = null; 
       mr = pn.matcher(msg);
       System.out.println("match result==>"+mr.find());
       pattern="*ClientException*Load*balancer*available server*"; 
       System.out.println(isMatch(msg, pattern));
       System.out.println(isMatchPattern(msg, pattern));
    }
	
}
